package com.centaline.androidsalesblog.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.text.TextUtils;

import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.centaline.androidsalesblog.application.MyLocation;
import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.model.databaseobject.CityDo;
import com.centaline.androidsalesblog.rx.map.RxMap;
import com.centaline.androidsalesblog.rx.request.RxRequest;
import com.orhanobut.logger.Logger;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * 用于首次启动获取城市列表、定位当前城市
 */
public class SplashService extends Service {

    private CompositeSubscription compositeSubscription = new CompositeSubscription();
    private ArrayList<CityDo> cityDoList = new ArrayList<>();
    private LocationClient locationClient;
    private SplashBinder splashBinder = new SplashBinder();
    private SplashCallback splashCallback;

    @Override
    public IBinder onBind(Intent intent) {
        return splashBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        locationClient = MyLocation.getLocationClient();
    }

    private void startRequest() {RxRequest.cityList(SplashService.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ArrayList<CityDo>>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        callback(1);
                    }

                    @Override
                    public void onNext(ArrayList<CityDo> cityDos) {
                        cityDoList.addAll(cityDos);
                        saveCityList();
                    }
                });
        compositeSubscription.add(RxMap.location(locationClient, true)
                .subscribe(new Action1<BDLocation>() {
                    @Override
                    public void call(BDLocation bdLocation) {
                        setData(bdLocation);
                    }
                }));
    }

    /**
     * 保存城市数据
     */
    private void saveCityList() {
        Observable.create(new Observable.OnSubscribe<Void>() {

            @Override
            public void call(Subscriber<? super Void> subscriber) {
                DataSupport.deleteAll(CityDo.class);
                DataSupport.saveAll(cityDoList);
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Void>() {
                    @Override
                    public void onCompleted() {
                        locationClient.start();
                    }

                    @Override
                    public void onError(Throwable e) {
                        callback(1);
                    }

                    @Override
                    public void onNext(Void aVoid) {

                    }
                });
    }

    /**
     * 处理
     */
    private void setData(final BDLocation bdLocation) {
        switch (bdLocation.getLocType()) {
            case 61:
            case 161:
                final String cityName = bdLocation.getCity();
                if (!TextUtils.isEmpty(cityName)) {
                    for (CityDo cityDo : cityDoList) {
                        if (cityName.contains(cityDo.getCityName()) ||
                                cityDo.getCityName().contains(cityName)) {
                            AppConstant.setNearbyEnable(SplashService.this, true);
                            AppConstant.exchangeCity(SplashService.this, cityDo);
                            break;
                        }
                    }
                }
                break;
            default:
                break;
        }
        callback(0);
    }

    private void callback(int status) {
        if (splashCallback != null) {
            splashCallback.callback(status);
        }
        stopSelf();
    }

    @Override
    public void onDestroy() {
        Logger.d("SplashService onDestroy");
        compositeSubscription.unsubscribe();
        super.onDestroy();
    }

    public class SplashBinder extends Binder {
        /**
         * 启动
         */
        public void splash(SplashCallback callback) {
            splashCallback = callback;
            startRequest();
        }
    }

    public interface SplashCallback {
        void callback(int status);
    }
}
